import React, { useEffect, useRef, useState } from 'react';
// 引入 echarts 核心模块
import * as echarts from 'echarts/core';
// 引入图表
import { BarChart, LineChart } from 'echarts/charts';
// 引入组件
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 引入特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入渲染器
import { CanvasRenderer } from 'echarts/renderers';
import { getSimpleChartDataFn, getSimpleKlineDataFn } from '../../api/data';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

export default function Echarts() {
  const chartDomRef = useRef(null);
  const chartInstanceRef = useRef(null);
  const [chartType, setChartType] = useState('bar'); // bar | kline
// 初始化图表
  const initChart = (option) => {
    if (chartDomRef.current) {
      // 初始化图表实例,第一个参数是容器的dom元素，第二个参数是配置项主题颜色
      chartInstanceRef.current = echarts.init(chartDomRef.current, 'dark');
      chartInstanceRef.current.setOption(option);
    }
  };
// 更新图表切换option
  const updateChart = (option) => {
    if (chartInstanceRef.current) {
      chartInstanceRef.current.setOption(option);
    } else {
      initChart(option);
    }
  };
// 获取数据并更新柱状图图表
  const fetchBarDataAndUpdate = async () => {
    try {
      const res = await getSimpleChartDataFn();
      if (res.code === '200') {
        const xAxisData = res.data.map(item => item.x);
        const seriesData = res.data.map(item => item.val);

        const option = {
          title: { text: '折线图1',link:"https://www.baidu.com",color:"#ccc",
            subtext: '折线图1的副标题',
            
           },
          //  提示文本
          tooltip: {},
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '销量',
              type: 'bar',
              data: seriesData,
              itemStyle: {
                color: '#5470c6'
              }
            }
          ]
        };

        updateChart(option);
      }
    } catch (error) {
      console.error('获取柱状图数据失败：', error);
    }
  };
// 更新折线图数据
  const fetchKLineDataAndUpdate = async () => {
    try {
      const res = await getSimpleKlineDataFn();
      if (res.code === '200') {
        const xAxisData = res.data.x;
        const seriesData = res.data.val; // K线图每个点是 [open, close, low, high]

        const option = {
          title: { text: res.message },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              const [open, close, low, high] = params[0].value;
              return `${params[0].axisValue}<br/>开: ${open} 收: ${close}<br/>低: ${low} 高: ${high}`;
            }
          },
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: 'K线',
              type: 'line',
              data: seriesData.map(val => val[1]), // 以收盘价为折线图显示
              lineStyle: {
                color: '#fac858'
              }
            }
          ]
        };

        updateChart(option);
      }
    } catch (error) {
      console.error('获取K线图数据失败：', error);
    }
  };

  useEffect(() => {
    // 默认加载柱状图
    fetchBarDataAndUpdate();

    return () => {
      if (chartInstanceRef.current) {
        chartInstanceRef.current.dispose();
        chartInstanceRef.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (chartType === 'bar') {
      fetchBarDataAndUpdate();
    } else if (chartType === 'kline') {
      fetchKLineDataAndUpdate();
    }
  }, [chartType]);

  return (
    <div>
      <div style={{ marginBottom: '10px' }}>
        <button onClick={() => setChartType('bar')} disabled={chartType === 'bar'}>
          显示柱状图
        </button>
        <button onClick={() => setChartType('kline')} disabled={chartType === 'kline'}>
          显示K线图
        </button>
      </div>
      <div id="main" ref={chartDomRef} style={{ width: '600px', height: '400px' }}>
        <h1>父组件</h1>
      </div>
    </div>
  );
}